package com.gegong.vmware.workstation.service.impl;

import com.gegong.vmware.workstation.NICDevices;
import com.gegong.vmware.workstation.VMPowerState;
import com.gegong.vmware.workstation.VMwareWorkstationManagementActions;
import com.gegong.vmware.workstation.VirtualMachine;
import com.gegong.vmware.workstation.exceptions.VMwareWorkstationManagementException;
import com.gegong.vmware.workstation.service.VMManagementService;
import com.gegong.vmware.workstation.service.VMNetworkAdaptersManagementService;
import com.gegong.vmware.workstation.service.VMPowerManagementService;
import com.gegong.vmware.workstation.utils.VmxFileUtils;
import okhttp3.Request;

public class DefaultVMNetworkAdaptersManagementServiceImpl implements VMNetworkAdaptersManagementService {
    private final VMManagementService managementService;

    private final VMPowerManagementService powerManagementService;

    public DefaultVMNetworkAdaptersManagementServiceImpl(VMManagementService managementService, VMPowerManagementService powerManagementService) {
        this.managementService = managementService;
        this.powerManagementService = powerManagementService;
    }

    @Override
    public NICDevices findAllNetworkAdapters(String id) throws VMwareWorkstationManagementException {
        VMwareWorkstationManagementActions.BaseAction action = VMwareWorkstationManagementActions.NetworkAdapter.FIND_ALL;
        String url = getUrl(action, id);
        Request request = new Request.Builder()
                .url(url)
                .headers(defaultHeaders)
                .build();
        return getResponse(request, VMwareWorkstationManagementActions.VM.FIND_ALL_VMS).getData(NICDevices.class);
    }

    @Override
    public void setMacAddress(String vmId, int slot, String macAddress) throws VMwareWorkstationManagementException {
        VirtualMachine virtualMachine = managementService.findById(vmId);
        VMPowerState powerState = powerManagementService.getPowerState(vmId);
        String vmName = managementService.getVmNameById(vmId);
        if (powerState.getState() != VMPowerState.States.poweredOff)
            throw new VMwareWorkstationManagementException(String.format("虚拟机%s当前的电源状态为%s,MAC地址修改无效", vmName, powerState));
        VmxFileUtils vmxFileUtils = new VmxFileUtils(virtualMachine.getPath());
        vmxFileUtils.setMacAddress(slot, macAddress);
    }
}
